# == Schema Information
#
# Table name: clues
#
#  id             :integer          not null, primary key
#  name           :string
#  mobile         :string           not null
#  address        :string
#  remark         :text
#  user_id        :integer          not null
#  account_id     :integer          not null
#  customer_id    :integer
#  created_at     :datetime         not null
#  updated_at     :datetime         not null
#  assign_user_id :integer
#  pound          :integer          default(0)
#  state          :boolean          default(TRUE)
#

class Clue < ActiveRecord::Base

  validates_uniqueness_of :mobile, message: '手机号已被使用'

  belongs_to :account
  belongs_to :user
  belongs_to :customer

  belongs_to :assign_user, class_name: 'User'

  scope :valid, -> {where(state: true)}

  scope :this_month, -> { where('created_at>=?',  Time.now.beginning_of_month) }
  scope :mine, -> (u_id) { where('user_id=? or assign_user_id=?', u_id, u_id) }

  before_create :gen_customer_id

  def self.like_search(_key)
    ransack(mobile_or_name_cont: _key).result
  end

  def gen_customer_id
    self.customer_id = 0 unless customer_id
  end

  def to_hash
    attributes.merge(
      assign_user_name: assign_user.try(:name)
    )
  end

  private

  def self.ransortable_attributes(auth_object = nil)
    column_names
  end

  def self.ransackable_attributes(auth_object = nil)
    ransortable_attributes + _ransackers.keys
  end

  ransacker :clue_info do |parent|
    Arel::Nodes::InfixOperation.new('||',
                                    Arel::Nodes::InfixOperation.new('||',
                                                                    parent.table[:mobile], Arel::Nodes.build_quoted(' ')),
    parent.table[:name])
  end

end
